/*
 * uart_svc.c
 *
 *  Created on: Jul 17, 2020
 *      Author: liwei
 */
#include "blink.h"
#include "esp_log.h"
#include "uart_svc.h"

QueueHandle_t mUart1_Queue;

/* read data frame from uart hardware and receice queue event */
uint8_t URT1_dRx(char* ucData, uint16_t* usLen)
{
    uart_event_t event;
    if (xQueueReceive(mUart1_Queue, (void*)&event, (portTickType)0)) {
        switch (event.type) {
        case UART_DATA:
            gpio_set_level(COM1_RX_R_LED, LED_ON);
            uart_read_bytes(UART_NUM_1, (uint8_t*)ucData, event.size, 0);
            *usLen = event.size;
            vTaskDelay(pdMS_TO_TICKS(10));
            gpio_set_level(COM1_RX_R_LED, LED_OFF);
            return (1);
        case UART_BUFFER_FULL:
            uart_flush_input(UART_NUM_1);
            xQueueReset(mUart1_Queue);
            break;
        default:
            break;
        }
    }
    return (0);
}

/* send modbus data frame to uart hardware */
int URT1_dData_Send(char* cData, uint16_t usLen)
{
    gpio_set_level(COM1_TX_G_LED, LED_ON);
    int i = uart_write_bytes(UART_NUM_1, cData, usLen);
    uart_flush_input(UART_NUM_1);
    vTaskDelay(pdMS_TO_TICKS(10));
    gpio_set_level(COM1_TX_G_LED, LED_OFF);
    return (i);
}

void URT1_vInit(UartConfigTPDF* tCfg)
{
    const uart_config_t uart_config = {
        .baud_rate = (tCfg->usBaudrateH << 16) + tCfg->usBaudrateL,
        .data_bits = tCfg->usWordSize,
        .parity = tCfg->usParity,
        .stop_bits = tCfg->usStopBits,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .source_clk = UART_SCLK_APB,
    };
    ESP_LOGE("52", ".baud_rate = %d", (tCfg->usBaudrateH << 16) + tCfg->usBaudrateL);
    uart_driver_install(UART_NUM_1, CONFIG_UART_RX_BUFFSIZE * 2, CONFIG_UART_RX_BUFFSIZE * 2, 20, &mUart1_Queue, 0);
    uart_param_config(UART_NUM_1, &uart_config);
    uart_set_pin(UART_NUM_1, CONFIG_UART_TX1_GPIO, CONFIG_UART_RX1_GPIO, CONFIG_UART_CT1_GPIO, UART_PIN_NO_CHANGE);
    uart_set_mode(UART_NUM_1, UART_MODE_RS485_HALF_DUPLEX);
}
